﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace WatiNCF.Helpers
{
    internal static class FileLoader
    {
        internal static string RewriteEmbeddedResource(string resourcePath, string outputPath)
        {
            Assembly testAssembly = Assembly.GetCallingAssembly();
            Debug.Assert(testAssembly.GetManifestResourceNames().FirstOrDefault(r => r == resourcePath) != null, string.Format("Failed to find resource '{0}'", resourcePath));

            using (Stream embeddedResourceStream = testAssembly.GetManifestResourceStream(resourcePath))
            {
                if (embeddedResourceStream != null)
                {
                    if (File.Exists(outputPath))
                    {
                        File.Delete(outputPath);
                    }

                    using (FileStream outputFileStream = new FileStream(outputPath, FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[embeddedResourceStream.Length];
                        embeddedResourceStream.Read(buffer, 0, buffer.Length);
                        embeddedResourceStream.Close();

                        outputFileStream.Write(buffer, 0, buffer.Length);
                        outputFileStream.Close();
                    }
                }
            }
            return outputPath;
        }

    }
}